import {createRouter, createWebHistory} from 'vue-router';
import Login from '../views/Login.vue';
import Home from "@/views/Home.vue";
import Publishblog from "@/views/Publishblog.vue";
import BlogDetail from "@/views/BlogDetail.vue";
import myblog from "@/views/Myblog.vue";
import api from "@/api/index";
import UserDetail from "@/views/UserDetail.vue";


const routes = [
    {path: '/login', component: Login},
    //  文章详情页
    {path: '/blog/:blogId', component: BlogDetail},
    {path: '/', component: Home},
    {path: '/UserDetail', component: UserDetail, meta: {requiresAuth: true}},


    {
        path: '/Publishblog', component: Publishblog, meta: {requiresAuth: true}
    },
    {
        path: '/my-blogs', component: myblog, meta: {requiresAuth: true} // 添加元信息，标识需要验证导航守卫回进行拦截
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});
//  设置导航守卫
router.beforeEach((to, from, next) => {
    const requiresAuth = to.meta.requiresAuth;
    // 如果目标页面不需要登录，直接放行
    if (!requiresAuth) {
        next();
        return;
    }
    //  需要拦截处理的页面

    api.get("/api/isLogin").then(res => {
            if (res.code === 200) {
                next()
            } else {
                next({
                    path: '/',
                });
                alert("你还未登录！");

            }
        }
    )
});


export default router;
